package whu.edu.assignment4.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import whu.edu.assignment4.dataobject.Product;
import whu.edu.assignment4.dataobject.User;
import whu.edu.assignment4.dataobject.UserProduct;
import whu.edu.assignment4.mapper.ProductMapper;
import whu.edu.assignment4.mapper.UserMapper;
import whu.edu.assignment4.service.ProductService;

import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Product findProductById(int pid) {
        return productMapper.selectById(pid);
    }

    @Override
    public List<Product> findAll() {
        return productMapper.selectAll();
    }

    @Override
    public int buyProducts(UserProduct userProduct) {
        User user = userMapper.selectUserByUid(userProduct.getUid());
        Product product = productMapper.selectById(userProduct.getPid());
        if(user == null || product == null) {
            return -1;
        }
        double totalPrice = userProduct.getNumber() * product.getPrice();
        userProduct.setTotalPrice(totalPrice);
        if(user.getBalance() < totalPrice) {
            return -2;
        }
        productMapper.insertUserProduct(userProduct);
        int result = userMapper.updateBalance(user.getBalance()-totalPrice, user.getUid());
        return result;
    }

    @Override
    public int addProduct(Product product) {
        return productMapper.insertProduct(product);
    }

    @Override
    public int deleteProduct(int pid) {
        return productMapper.deleteProductById(pid);
    }

    @Override
    public int updateProduct(Product product) {
        return productMapper.updateProduct(product);
    }
}
